<?php

namespace app\api\controller;

use addons\third\library\Service;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Session;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['merchantTeacher','merchantTeacherEditComment','merchantTeacherEdit','couponAllList','login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wxRegister','getIsRegister'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 第三方登录[绑定] 小程序
     */
    public function wxLogin()
    {
        $code = $this->request->post("code");
        $invitecode = $this->request->post("invitecode",0);
        //file_put_contents(time().$code.".txt",$invitecode);
        $WxUser = $this->request->post("rawData/a");
        if (!$code || !$WxUser) {
            $this->error("参数不正确");
        }
        $third = get_addon_info('third');
        if (!$third || !$third['state']) {
            $this->error("请在后台插件管理安装并配置第三方登录插件");
        }
        $params = [
            'appid'      => Config::get('shop.wx_appid'),
            'secret'     => Config::get('shop.wx_app_secret'),
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $WxUser['nickName'] = "优品用户";
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $userinfo = [
                    'platform'      => 'wechat',
                    'apptype'       => 'miniapp',
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => $WxUser['nickName'],
                        'avatar'   => $WxUser['avatarUrl']
                    ],
                    'openname'      => $WxUser['nickName'],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'unionid'       => isset($json['unionid']) ? $json['unionid'] : ''
                ];

                $third = [
                    'nickname' => $WxUser['nickName'],
                    'avatar'   => $WxUser['avatarUrl']
                ];
                $user = null;

                if ($this->auth->isLogin() || Service::isBindThird($userinfo['platform'], $userinfo['openid'], $userinfo['apptype'], $userinfo['unionid'])) {
                    $extend['parent_user_id'] = $invitecode;
                    Service::connect($userinfo['platform'], $userinfo,$extend);
                    $user = $this->auth->getUserinfo();
                    $user['avatar'] = cdnurl($user['avatar'], true);
                } else {
                    Session::set('third-userinfo', $userinfo);
                }
                // file_put_contents(time().$code."2.txt",$invitecode);
                $this->success('授权成功!', ['user' => $user, 'third' => $third]);
            }
        }
        //file_put_contents(time().$code."1.txt",$result['msg']);
        $this->error("授权失败," . $result['msg']);
    }


    /**
     * @return void
     * 用户信息
     */
    public function info(){
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $data['userinfo']['all_score'] =  sprintf("%.2f",$data['userinfo']['score'] + $data['userinfo']['fixed_score']);
        $this->success(__('successful'), $data);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 积分明细
     */
    public function getScoreLog(){
        $is_fixed = $this->request->post("is_fixed", 0);//0自由积分 1固定积分
        $page = $this->request->post("page", 1);
        $per_page = $this->request->post("per_page", 15);
        $user = $this->auth->getUser();

        $where['user_id'] = $user->id;
        $where['is_fixed'] = $is_fixed;
        $total = Db::name("user_score_log")
            ->where($where)->count();
        $str_num = ($page - 1) * $per_page;
        $list = Db::name("user_score_log")
            ->where($where)
            ->order("id desc")
            ->limit($str_num, $per_page)
            ->select();
        foreach ($list as $k=>$v){
            $list[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        $re_data['list'] = $list;
        if($is_fixed == 1){
            $re_data['score'] = $this->auth->fixed_score;
        }else{
            $re_data['score'] = $this->auth->score;
        }

        $re_data['current_page'] = $page;
        $re_data['last_page'] = ceil($total/$per_page);
        $re_data['total'] = $total;
        $re_data['per_page'] = $per_page;
        $this->success('我的积分记录', $re_data);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 优惠券
     */
    public function getCouponLog(){
        $is_used = $this->request->post("is_used");//1=未使用,2=已使用3 已过期
        $page = $this->request->post("page", 1);
        $per_page = $this->request->post("per_page", 15);
        $user = $this->auth->getUser();

        $where['user_id'] = $user->id;
        if($is_used){
            $where['is_used'] = $is_used;
        }

        $total = Db::name("user_coupon")
            ->where($where)->count();
        $str_num = ($page - 1) * $per_page;
        $list = Db::name("user_coupon")
            ->where($where)
            ->order("id desc")
            ->limit($str_num, $per_page)
            ->select();
        foreach ($list as $k=>$v){
            $coupon_type = Db::name("coupon")->where(['id'=>$v['coupon_id']])->value('type');
            $coupon_name = Db::name("coupon")->where(['id'=>$v['coupon_id']])->value('name');
            $list[$k]['begin_time'] = date('Y-m-d',$v['begin_time']);
            $list[$k]['expire_time'] = date('Y-m-d',$v['expire_time']);
            $list[$k]['createtime'] = date('Y-m-d',$v['createtime']);
            $list[$k]['coupon_type'] =$coupon_type;
            $list[$k]['coupon_name'] =$coupon_name;
            $list[$k]['merchant_name'] =Db::name("merchant")->where(['id'=>$v['merchant_user_id']])->value("name");
        }
        $re_data['list'] = $list;
        $re_data['current_page'] = $page;
        $re_data['last_page'] = ceil($total/$per_page);
        $re_data['total'] = $total;
        $re_data['per_page'] = $per_page;
        $this->success('我的积分记录', $re_data);
    }
    public function getIsRegister(){
        $code = $this->request->post("applet_code");
        $params = [
            'appid'      => 'wxfc449efa209ab07e',
            'secret'     => '81d7d2a3dceb39882e141c931936f346',
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        $json = (array)json_decode($result['msg'], true);
        if (isset($json['openid'])) {
            $data = Db::name("user")->where(['openid'=>$json['openid']])->find();
            if($data){
                $ret = $this->auth->direct($data['id']);
                $re_data['is_register'] = false;
                $re_data['info'] = $ret;
                $re_data['token'] = $this->auth->getToken();
            }else{
                $re_data['is_register'] = true;
            }
           $this->success("成功",$re_data);

        }
        $this->error("失败," . $result['msg']);
    }
    public function wxRegister(){
        $avatar = $this->request->post("avatar");
        $nickname = $this->request->post("nickname");
        $encryptedData = $this->request->post('encryptedData', '', 'trim');
        $iv = $this->request->post('iv');
        $mobile_code = $this->request->post("mobile_code");
        $applet_code = $this->request->post("applet_code");
        $params = [
            'appid'      => 'wxfc449efa209ab07e',
            'secret'     => '81d7d2a3dceb39882e141c931936f346',
            'js_code'    => $applet_code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            ///var_dump($json);exit;
            $aesIV = base64_decode($iv);
            $aesCipher = base64_decode($encryptedData);
            $aesKey = base64_decode($json['session_key']);
            $re = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
            $data = json_decode($re, true);
            if ($data) {
              //  $user = \app\common\model\User::getByMobile($data['phoneNumber']);
                $user = Db::name("user")->where(['mobile'=>$data['phoneNumber']])->find();
                if ($user) {
                    if ($user['status'] != 'normal') {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user['id']);
                } else {
                    $ret = $this->auth->register($data['phoneNumber'], Random::alnum(), '', $data['phoneNumber'], ["openid"=>$json['openid'],'avatar'=>$avatar,'nickname'=>$nickname]);
                }
                if ($ret) {
                    $data = ['token' => $this->auth->getToken()];
                    $this->success(__('Logged in successful'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            } else {
                $this->error("配置参数错误");
            }
        } else {
            $this->error("授权失败");
        }
    }
    public function myTeacher(){
        $user = $this->auth->getUser();
        $merchant_teacher_id = Db::name("merchant_teacher")->where(['user_id'=>$user->id])->value("id");
        $list = Db::name("user_recharge_card")->where(['merchant_teacher_id'=>$merchant_teacher_id])->field("id,course_id,sum,surplus_sum")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            $card_data = Db::name("course")->where(['id'=>$v['course_id']])->find();
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($card_data['image'], true);
            $list['data'][$k]['name'] =  $card_data['name'];
        }
        $this->success("课程预约情况",$list);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 老师课程预约情况 - 预约情况
     */
    public function coursePre(){
        $card_id = $this->request->post("card_id");
        $list = Db::name("course_order_pre")->where(['user_recharge_card_id'=>$card_id])->field("id,user_id,day,course_id,type,user_recharge_card_id,status")->order("id desc")->paginate()->toArray();
        $course_id= 0;
        foreach ($list['data'] as $k=>$v){
            $usr_data = Db::name("user")->where(['id'=>$v['user_id']])->find();
            $list['data'][$k]['avatar'] =  cdnurl($usr_data['avatar'], true);
            $list['data'][$k]['nickname'] =  $usr_data['nickname'];
            $list['data'][$k]['mobile'] =  $usr_data['mobile'];
            $list['data'][$k]['day'] =  date('Y-m-d',$v['day']);
            $course_id= $v['course_id'];
            if($v['type'] == 2){
                $data = Db::name("user_recharge_card")->where(['id'=>$v['user_recharge_card_id']])->find();
                $list['data'][$k]['card_name'] =  Db::name("card")->where(['id'=>$data['card_id']])->value("name");
            }
        }
        $card_data = Db::name("course")->where(['id'=>$course_id])->find();
        // var_dump($v);exit;
        $re_data['list'] =  $list;
        $re_data['image'] =  cdnurl($card_data['image'], true);
        $re_data['name'] =  $card_data['name'];
        $re_data['pre_sum'] = Db::name("course_order_pre")->where(['user_recharge_card_id'=>$card_id])->count();
        $this->success("预约情况",$re_data);
    }
    public function merchantList(){
       /* $user = $this->auth->getUser();
        $list = Db::name("merchant")->order("id desc")->paginate()->toArray();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);
            $merchant_score = self::getMerchantScore($user->id,$v['id']);
            $list['data'][$k]['merchant_score'] = $merchant_score;
        }
        // 将数据转化为数组
        //$list = $list->toArray();
        // 返回数据
        $re_data['fixed_score'] = $user->fixed_score;
        $re_data['list'] = $list;
        $this->success('商家列表', $re_data);*/
        $user = $this->auth->getUser();
        $list = Db::name("user_score_log")
            ->where(['user_id'=>$user->id,'surplus_score'=>['>',0]])
            ->field('id,merchant_user_id,surplus_score,end_time')
            ->order("id desc")->paginate()->toArray();
        //echo Db::name("user_score_log")->getLastSql();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            $merchant = Db::name("merchant")->where(['id'=>$v['merchant_user_id']])->find();
            $list['data'][$k]['merchant_image'] =  cdnurl($merchant['image'], true);
            $list['data'][$k]['merchant_name'] = $merchant['name'];
            $list['data'][$k]['merchant_id'] = $merchant['id'];
            $list['data'][$k]['description'] = $merchant['description'];
            $list['data'][$k]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
        }
        // 将数据转化为数组
        //$list = $list->toArray();
        // 返回数据
        $re_data['fixed_score'] = $user->fixed_score;
        $re_data['list'] = $list;
        $this->success('商家列表', $re_data);
    }
    public static function getMerchantScore($user_id,$merchant_user_id){
        $list = Db::name("user_score_log")->where(['user_id'=>$user_id,'merchant_user_id'=>$merchant_user_id,'is_fixed'=>1])->select();
        $vlu = 0;
        if($list){
            foreach ($list as $k=>$v){
                if($v['before'] > $v['after']){
                    $vlu -= abs($v['score']);
                }else{
                    $vlu += abs($v['score']);
                }
            }
        }
        return $vlu;
    }
    public function merchantEdit(){
        $id = $this->request->post("merchant_id");
        $data = Db::name("merchant")->where(['id'=>$id])->find();
        $data['image'] =  cdnurl($data['image'], true);
        $this->success("商家详情",$data);
    }
    public function merchantGoodsList(){
        $merchant_id = $this->request->post("merchant_id");
        $where['id'] = ['>',0];
        if($merchant_id){
            $where['merchant_user_id'] = $merchant_id;
        }
        // 获取分页数据
        $list = Db::name("goods")->where($where)->field("id,image,sales,price,name")->order("id desc")->paginate()->toArray();
        // $list = $list->toArray();
        // var_dump($list);exit;
        //  var_dump($list['data']);
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);
        }
        // 将数据转化为数组
        //$list = $list->toArray();
        // 返回数据
        $this->success('商家商品列表', $list);
    }
    public function merchantCourseList(){
        $merchant_id = $this->request->post("merchant_id");
        $where['id'] = ['>',0];
        if($merchant_id){
            $where['merchant_user_id'] = $merchant_id;
        }
        $list = Db::name("course")->where($where)->field("id,name,price,image,sales")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);

        }
        $this->success('商家课程列表', $list);
    }
    public function couponList(){
        $merchant_id = $this->request->post("merchant_id");
        $where['type'] = 2;
        $where['merchant_user_id'] = $merchant_id;
        $where['begintime'] = ['<',time()];
        $where['endtime'] = ['>',time()];
        $list = Db::name("coupon")->where($where)->field("id,name,money,number,type,endtime,content")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['endtime'] =  date('Y-m-d',$v['endtime']);
        }
        $this->success('优惠券列表', $list);
    }
    public function couponAllList(){

        $page = $this->request->post("page", 1);
        $per_page = $this->request->post("per_page", 15);

        $where['begintime'] = ['<',time()];
        $where['endtime'] = ['>',time()];
        $where['type'] = 1;
        $total = Db::name("coupon")->where($where)->where('give_num>received_num')->count();
        $str_num = ($page - 1) * $per_page;
        $list = Db::name("coupon")->where($where)->where('give_num>received_num')
            ->field("id,name,money,number,type,endtime,content,give_num,received_num")->order("id desc")
            ->limit($str_num, $per_page)
            ->select();
        foreach ($list as $k=>$v){
            // var_dump($v);exit;
            $list[$k]['endtime'] =  date('Y-m-d',$v['endtime']);
        }
        $re_data['data'] = $list;
        $re_data['current_page'] = $page;
        $re_data['last_page'] = ceil($total/$per_page);
        $re_data['total'] = $total;
        $re_data['per_page'] = $per_page;

        $this->success('优惠券列表', $re_data);
    }
    public function couponEdit(){
        $id = $this->request->post("id");

        $where['id'] = $id;
        $where['begintime'] = ['<',time()];
        $where['endtime'] = ['>',time()];
        $data = Db::name("coupon")->where($where)->find();
        if(!$data){
            $this->error("数据有误");
        }
        $data['begintime'] =  date('Y-m-d',$data['begintime']);
        $data['endtime'] =  date('Y-m-d',$data['endtime']);
        $data['use_begtime'] =  date('Y-m-d',$data['use_begtime']);
        $data['use_endtime'] =  date('Y-m-d',$data['use_endtime']);

        $this->success("优惠券详情",$data);
    }
    public function couponPay(){
        $user = $this->auth->getUser();
        $id = $this->request->post("id");
        $where['begintime'] = ['<',time()];
        $where['endtime'] = ['>',time()];
        $where['id'] = $id;
        $data = Db::name("coupon")->where(['id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        if($data['type'] == 2){
            $merchant_score = self::getMerchantScore($user->id,$data['merchant_user_id']);
            if($merchant_score < $data['score']){
                $this->error("积分不足");
            }
        }else{
            if($user->score < $data['score']){
                $this->error("积分不足");
            }
        }

        if($data['received_num'] >= $data['give_num']){
            $this->error("可领取数量不足");
        }
        $user_count = Db::name("user_coupon")->where(['user_id'=>$user->id,'coupon_id'=>$id])->count();
        if($user_count >= $data['allow_num']){
            $this->error("达到每人领取数量的上限");
        }
        $in_data['coupon_id'] = $data['id'];
        $in_data['user_id'] = $user->id;
        $in_data['begin_time'] = $data['use_begtime'];
        $in_data['expire_time'] = $data['use_endtime'];
        $in_data['use_begtime'] = $data['use_begtime'];
        $in_data['use_endtime'] = $data['use_endtime'];
        $in_data['money'] = $data['money'];
        $in_data['number'] = $data['number'];
        $in_data['type'] = $data['type'];
        $in_data['merchant_user_id'] = $data['merchant_user_id'];
        $in_data['createtime'] = time();
        Db::name("user_coupon")->insertGetId($in_data);
        Db::name("coupon")->where(['id'=>$id])->setInc('received_num');

        if($data['type'] == 2){
            \app\common\model\User::score($data['score'], $data['merchant_user_id'], "用户领取优惠券");
            \app\common\model\User::score(-$data['score'], $this->auth->id, "领取优惠券消耗积分",1,$data['merchant_user_id']);
        }else{
            \app\common\model\User::score(-$data['score'], $this->auth->id, "领取优惠券消耗积分",0,$data['merchant_user_id']);
        }
        $this->success("领取成功");
    }
    public function merchantTeacher(){
        $list = Db::name("merchant_teacher")->order("id desc")->paginate()->toArray();
        foreach ($list['data'] as $k=>$v){
            // var_dump($v);exit;
            $list['data'][$k]['image'] =  cdnurl($v['image'], true);
        }
        $this->success('老师列表', $list);
    }
    public function merchantTeacherEdit(){
        $id = $this->request->post("id");
        $data = Db::name("merchant_teacher")->where(['id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $data['image'] = cdnurl($data['image'],true);
        $this->success('老师详情',$data);
    }
    public function merchantTeacherEditComment(){
        $id = $this->request->post("id");
        if(!$id){
            $this->error("缺少必传参数");
        }
        $comment_list = Db::name("course_comment")->where(['merchant_teacher_id'=>$id])->order('id desc')->paginate()->toArray();
        foreach ($comment_list['data'] as $k=>$v){
            $user_data = Db::name("user")->where(['id'=>$v['user_id']])->find();
            $comment_list['data'][$k]['nickname'] = $user_data['nickname'];
            $comment_list['data'][$k]['avatar'] = cdnurl($user_data['avatar'],true);
            $comment_list['data'][$k]['createtime'] =  date('Y-m-d',$v['createtime']);

            $images_arr1 = explode(',',$v['images']);
            $images_str1 = '';
            foreach ($images_arr1 as $k1=>$v1){
                $images_str1 .= cdnurl($v1,true).',';
            }
            $comment_list['data'][$k]['images']= explode(',',trim($images_str1,','));
        }
        $this->success("老师的评价",$comment_list);
    }
}
